package com.fastmms.utils;

public class ByteUtil {
    public static byte[] toByteArray(int i) {
        byte[] data = new byte[4];
        data[0] = (byte) ((i >>> 24) & 0xFF);
        data[1] = (byte) ((i >>> 16) & 0xFF);
        data[2] = (byte) ((i >>> 8) & 0xFF);
        data[3] = (byte) (i & 0xFF);
        return data;
    }

    public static int toInt(byte[] data, int off) {
        return (data[off] & 0xFF) << 24
                | (data[off + 1] & 0xFF) << 16
                | (data[off + 2] & 0xFF) << 8
                | (data[off + 3] & 0xFF);
    }

    /**
     * long类型转byte[] (大端)
     * @param n
     * @return
     */
    public static byte[] longToBytesBig(long n) {
        byte[] b = new byte[8];
        b[7] = (byte) (n & 0xff);
        b[6] = (byte) (n >> 8  & 0xff);
        b[5] = (byte) (n >> 16 & 0xff);
        b[4] = (byte) (n >> 24 & 0xff);
        b[3] = (byte) (n >> 32 & 0xff);
        b[2] = (byte) (n >> 40 & 0xff);
        b[1] = (byte) (n >> 48 & 0xff);
        b[0] = (byte) (n >> 56 & 0xff);
        return b;
    }

    /**
     * byte[]转long类型(大端)
     * @param array
     * @return
     */
    public static long bytesToLongBig( byte[] array , int off)
    {
        return ((((long) array[ off ] & 0xff) << 56)
                | (((long) array[ off +1] & 0xff) << 48)
                | (((long) array[ off +2] & 0xff) << 40)
                | (((long) array[ off +3] & 0xff) << 32)
                | (((long) array[ off +4] & 0xff) << 24)
                | (((long) array[ off +5] & 0xff) << 16)
                | (((long) array[ off +6] & 0xff) << 8)
                | (((long) array[ off +7] & 0xff) << 0));
    }

}
